<?php

namespace App\Http\Controllers;

use App\Models\RolePermission;
use App\Models\UserRole;
use Illuminate\Auth\Events\Failed;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use App\Models\Users;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Collection;

class AuthController extends BaseController
{

    public function login(Request $request): \Illuminate\Http\JsonResponse
    {


        $credentials = $request->only('username', 'password');

        if (count($credentials) < 2) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $user = Users::where('name', $credentials['username'])
            ->where('password', md5($credentials['password']))
            ->first();
        if(!$user){
            return  Failed(40004,["File"=>"AuthController","Line"=>__LINE__]);
        }
        if($user->is_locked ==1){
            return Failed(40007,["File"=>"AuthController","Line"=>__LINE__]);
        }

        if($user->status!=1){
            return Failed(40005,["File"=>"AuthController","Line"=>__LINE__]);
        }

        $user_extra_per = $user::with([
            "extraPermissions" => function ($query) {
                $query->select('permission.id as per_id', 'parentid', 'name', 'api_route', 'web_route', 'method', 'no',
                    'is_need_auth', 'is_system_menu', 'permission.status');
                $query->where("user_extra_permission.status", 1);
                $query->where("permission.status", 1);
                $query->where("is_need_auth", 1);
            }
        ])->first()->toArray()['extra_permissions'];
        $user_extra_permissions = [];
        foreach ($user_extra_per as  $vo){
            $user_extra_permissions[$vo['per_id']] =(array)$vo;
        }

        $customClaims = ['extra_permission' => $user_extra_permissions, 'code' => 123132];

        $login_ip = $request->getClientIp();
        $login_at = date("Y_m-d H:i:s");


        if (empty($user) || !$token = JWTAuth::customClaims( $customClaims)->fromUser($user)) {
            return Failed(40001,["File"=>"AuthController","Line"=>__LINE__]);
        }
        $data = [
            "last_login_at"=>$login_at,
            "last_login_ip"=>$login_ip,
            "updated_at"=>date("Y-m-d H:i:s"),
            "token"=>$token
        ];

        if(!$user->update($data)){
            return Failed(11010,["File"=>"AuthController","Line"=>__LINE__]);
        }
        // dd($token);

        return $this->respondWithToken(200,$token);
    }

    public function me(Request $request): \Illuminate\Http\JsonResponse
    {
        $data = [
            "user_info" => $this->user,
            "user_role" => $this->getUserRoles(),
            "user_permissions" => array_values($this->getUserPermissionAndMenu()['permission']),
            "user_menus" => $this->getUserPermissionAndMenu()['menu']
        ];
        return $this->success(200,'获取信息成功',$data);
    }

    public function logout(): \Illuminate\Http\JsonResponse
    {
//        auth('api')->logout();
        Auth::guard('api')->logout();
        return Success(20001,["File"=>"AuthController","Line"=>50]);
    }



    public function refresh(): \Illuminate\Http\JsonResponse
    {
        $old_token = JWTAuth::getToken()->get();

        $user = JWTAuth::user();
        JWTAuth::invalidate();

        $user = Users::where('name', $user->name)
            ->first();

        if (empty($user) || !$new_token = JWTAuth::fromUser($user)) {
            return Failed(40001,["File"=>"AuthController","Line"=>64]);
        }

        return $this->success(40006,[
            'access_token' => $new_token,
            'old_access_token' => $old_token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);

    }


    protected function respondWithToken($code,$token): \Illuminate\Http\JsonResponse
    {
        return $this->success($code,'',[
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }

}
